<?php

namespace App\Http\Controllers\Admin;

use App\Models\SatisfactionSurvey;
use App\Models\SatisfactionSurveyReply;
use App\Validate\SatisfactionSurveyValidate;
use Illuminate\Support\Facades\DB;

/**
 * 满意度调查类
 * Class Survey
 * @package app\api\controller
 */
class SatisfactionSurveyController extends CommonController
{


    // 自动验证
    public $validate = null;
    public $model = null;

    /**
     * 实例化满意度调查验证类
     * Survey constructor.
     */
    public function __construct()
    {
        parent::__construct();

        $this->validate = new SatisfactionSurveyValidate();
        $this->model = new SatisfactionSurvey();
    }

    /**
     * 满意度调查列表
     * @param page 默认为 1
     * @param limit 限制条数 默认为 10
     * @param keywords 检索内容
     * @param is_play int 是否发布 1.发布 2.未发布    默认1
     */
    public function lists()
    {
        $page = intval($this->request->page) ?: 1;
        $limit = $this->request->limit ?: 10;
        $keywords = $this->request->keywords;
        $is_play = $this->request->is_play;

        // 获取数据
        $res = $this->model->select('id', 'survey_name', 'intro', 'start_time', 'end_time', 'create_time', 'is_play', 'reply_num', 'day_number', 'total_number')
            ->where("is_del", 1)
            ->where(function ($query) use ($keywords) {
                if (!empty($keywords)) {
                    $query->where('survey_name', 'like', "%$keywords%");
                }
            })
            ->where(function ($query) use ($is_play) {
                if (!empty($is_play)) {
                    $query->where('is_play', $is_play);
                }
            })
            ->orderByDesc("id")
            ->paginate($limit)
            ->toArray();

        $surveyReplyModel = new SatisfactionSurveyReply();
        $res = $this->disPageData($res);
        foreach ($res['data'] as $key => $val) {
            if ($val['end_time'] < date('Y-m-d H:i:s')) {
                $res['data'][$key]['past_due'] = true; //已过期
            } else {
                $res['data'][$key]['past_due'] = false; //未过期
            }
            //计算满意度
            $satisfaction = $surveyReplyModel->getUserSubmitCount($val['id'], null, null, 1); //满意数量
            $not_satisfaction = $surveyReplyModel->getUserSubmitCount($val['id'], null, null, 2); //不满意数量

            $res['data'][$key]['satisfaction'] = $satisfaction;
            $res['data'][$key]['not_satisfaction'] = $not_satisfaction;

            $total_number = $satisfaction + $not_satisfaction; //
            $res['data'][$key]['satisfaction_percent'] = $total_number ? sprintf("%.2f", $satisfaction / $total_number) : '0.00';
            $res['data'][$key]['not_satisfaction_percent'] = $total_number ? sprintf("%.2f", (1 - $res['data'][$key]['satisfaction_percent'])) : '0.00';

            $res['data'][$key]['intro'] = strip_tags($val['intro']);
            $res['data'][$key][$this->list_index_key] = $this->addSerialNumberOne($key, $page, $limit);
        }
        // 反馈数据
        if ($res['data']) {
            return $this->returnApi(200, "获取成功", true, $res);
        }
        return $this->returnApi(203, "暂无数据");
    }


    /**
     * 满意度调查详情
     * @param $id ：满意度调查id
     */
    public function detail()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('detail')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        // 获取满意度调查是否存在
        $res = $this->model->select('id', 'survey_name', 'intro', 'start_time', 'end_time', 'create_time', 'is_play', 'reply_num', 'day_number', 'total_number')
            ->where("is_del", 1)
            ->find($this->request->id);

        if (empty($res)) {
            return $this->returnApi(203, "暂无数据");
        }

        if ($res['end_time'] < date('Y-m-d H:i:s')) {
            $res['past_due'] = true; //已过期
        } else {
            $res['past_due'] = false; //未过期
        }

        return $this->returnApi(200, "获取成功", true, $res);
    }


    /**
     * 添加调查问题
     * @param survey_name 问卷名称
     * @param intro 问卷简介
     * @param start_time 问卷开始时间
     * @param end_time 问卷结束时间
     * @param is_play 是否发布的状态   1 已发布   2 未发布
     */
    public function add()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('add')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $is_exists = $this->model->nameIsExists($this->request->survey_name, 'survey_name');

        if ($is_exists) {
            return $this->returnApi(202, "此名称已存在");
        }

        DB::beginTransaction();
        try {
            $this->model->add($this->request->all());

            DB::commit();
            return $this->returnApi(200, "新增成功", true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage() ? $e->getMessage() : "新增失败");
        }
    }
    /**
     * 修改调查问题
     * @param id   问卷id
     * @param survey_name 问卷名称
     * @param intro 问卷简介
     * @param start_time 问卷开始时间
     * @param end_time 问卷结束时间
     * @param is_play 是否发布的状态   1 已发布   2 未发布
     */
    public function change()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('change')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $is_exists = $this->model->nameIsExists($this->request->survey_name, 'survey_name', $this->request->id);

        if ($is_exists) {
            return $this->returnApi(202, "此名称已存在");
        }

        DB::beginTransaction();
        try {
            $this->model->change($this->request->all());

            DB::commit();
            return $this->returnApi(200, "修改成功", true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage() ? $e->getMessage() : "修改失败");
        }
    }

    /**
     * 满意度调查删除
     * @param id      问卷id
     */
    public function del()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('del')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $id = $this->request->id; //问卷id
        $surveyInfo = $this->model->find($id);
        if (empty($surveyInfo)) {
            return $this->returnApi(202, '此问卷不存在');
        }
        if ($surveyInfo['is_play'] == 1) {
            return $this->returnApi(202, '此问卷已发布，禁止删除');
        }
        if ($surveyInfo['reply_num'] !== 0) {
            return $this->returnApi(202, '此问卷已有人回答，禁止删除');
        }

        $res = $surveyInfo->is_del = 2;
        $res = $surveyInfo->change_time = date('Y-m-d H:i:s');
        $res = $surveyInfo->save();
        if ($res) {
            return $this->returnApi(200, '删除成功', true);
        }
        return $this->returnApi(202, '删除失败');
    }

    /**
     * 满意度调查 撤销  与 发布
     * @param id      问卷id
     * @param is_play   1 发布   2 撤销
     */
    public function cancelAndRelease()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('cancelAndRelease')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }


        $id = $this->request->id; //问卷id
        $is_play = $this->request->is_play; //问卷状态
        $surveyInfo = $this->model->where('is_del', 1)->find($id);
        if (empty($surveyInfo)) {
            return $this->returnApi(202, '此问卷不存在');
        }
        if ($is_play == 1 && $surveyInfo->end_time < date('Y-m-d H:i:s')) {
            return $this->returnApi(202, '此问卷已过期，不允许发布');
        }

        $res = $surveyInfo->is_play = $is_play;
        $res = $surveyInfo->change_time = date('Y-m-d H:i:s');
        $res = $surveyInfo->save();

        if ($res) {
            return $this->returnApi(200, '操作成功', true);
        }
        return $this->returnApi(202, '操作失败');
    }
}
